﻿using System.Collections.Generic;
using System.Linq;
using Xoohoo.Infrastructure;
using Xoohoo.Models;
using Xoohoo.Repositories;
using Xoohoo.ModelValidation;
using System;
using Xoohoo.Models.InputModels;

namespace Xoohoo.Services
{
    public class SiteService : ISiteService
    {
        private readonly ISiteRepository _repository;
        private readonly ICacheModule _cache;
        private readonly ILoggingModule _logger;
        private readonly string _siteCacheKeyFormat = "Site";

        public SiteService(ISiteRepository repository, IModuleRegistry modulesLoaded)
        {
            this._repository = repository;

            IEnumerable<ICacheModule> cacheModules = modulesLoaded.GetModules<ICacheModule>();
            this._cache = cacheModules != null && cacheModules.Count() > 0 ? cacheModules.Reverse().First() : null;

            IEnumerable<ILoggingModule> logModules = modulesLoaded.GetModules<ILoggingModule>();
            this._logger = logModules != null && logModules.Count() > 0 ? logModules.Reverse().First() : null;
        }
        public Site GetItem()
        {
            return
                _cache != null
                ? _cache.GetItem<Site>(_siteCacheKeyFormat, () => _repository.GetItem(), null)
                : _repository.GetItem();
        }
        public bool Save(SiteInput site)
        {
            //保存实体
            _repository.Save(site);
            //清空Site实体缓存
            //cache.Invalidate(siteCacheKeyFormat);

            _logger.Info("修改系统配置");

            return true;
        }
        public bool Restart()
        {
            try
            {
                string webConfig = System.Web.HttpRuntime.AppDomainAppPath + "Web.Config";
                System.IO.File.SetLastWriteTime(webConfig, System.DateTime.Now);
                _logger.Info("重新启动站点成功");
                return true;
            }
            catch(Exception e) {
                _logger.Error("重新启动站点失败", e);
                return false;
            }
        }
    }
}
